$(function() {

	var UserModel = Backbone.Model.extend({
		defaults: function() {
			return {
				id: "d"+parseInt(Math.random() * 1321413),
				lat : 0 , 
			 	lon : 0,
			 	categoria : ["c1","c2","c3","c4","c5","c6"]
			};
		}
	});

	var UserCollection = Backbone.Collection.extend({
		model: UserModel,
		parse: function(response){
		       return response.CLient;
		},
		initialize:function(){
			me = this;
		    var hr = new XMLHttpRequest();
		    hr.open("GET", '/pediOnline/js/example.json', true);
		    hr.setRequestHeader("Content-type", "application/json", true);
		    hr.onreadystatechange = function() {
			    if(hr.readyState == 4 && hr.status == 200) {
				    var data = JSON.parse(hr.responseText);
				    for(var obj in data){
				    	me.add(data[obj]);
				    }
			    }
		    }
		    hr.send(null);
	}
	});
		
	

	function addUser(data) {
		try {
			users.add(data);
		} catch (error) {
			console.log(error.message);
		}
	};


	function updateTable() {
		var $tbody = $(".imanes-usuarios");
		var template = $.trim($("[data-template-name='user-row']").html() || "Row template not found!");

		$tbody.empty();

		users.each(function(user){
			$tbody.append(Mustache.render(template, user.toJSON()));
		}, this);
	};
	
	var users = new UserCollection();
	
	users.on("add remove" , updateTable);
	
	updateTable();
	
});

//TODO
//	$(".add").click(function(event) {
//		console.log("click");
//		addUser({
//			id: parseInt(Math.random() * 1321413),
//			lat : -34.580936007738536 , 
//		 	lon : -58.70537477111816,
//		 	categoria : ["c1","c2","c3","c4","c5","c6"]
//		});
//		
//	});

//	function removeUser(userId) {
//		users.remove(users.get(userId));
//	};

//	$("body").on("click", ".delete", function(event){
//		removeUser($(event.currentTarget).parent().parent().data("user-id"));
//	});